{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "eff0c6e8",
   "metadata": {},
   "source": [
    "## 优化百度ASR接口"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "a7884efc",
   "metadata": {},
   "outputs": [],
   "source": [
    "import ASR"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "c0f98abf",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'24.a7f4f58c102b809a38edb685eb2f7741.2592000.1655472906.282335-26192069'"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 获取token\n",
    "API_KEY = '6zgxEabrybKwGnwGBGKq0N4m'\n",
    "SECRET_KEY = 'j7sb4h3CQ3iISZVCuF2wlSfztSDXVYGR'\n",
    "\n",
    "token = ASR.fetch_token(API_KEY,SECRET_KEY)\n",
    "token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "20ed9af0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 准备音频文件\n",
    "import speech_recognition\n",
    "r = speech_recognition.Recognizer()\n",
    "\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将数据保存到wav文件中\n",
    "with open(\"1.wav\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "ba436f6a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'{\"corpus_no\":\"7099069466623732912\",\"err_msg\":\"success.\",\"err_no\":0,\"result\":[\"你好。\"],\"sn\":\"77906641641652880913\"}\\n'"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 调用asr函数\n",
    "result = ASR.asr(token)\n",
    "result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "a83a52a6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'corpus_no': '7099069466623732912',\n",
       " 'err_msg': 'success.',\n",
       " 'err_no': 0,\n",
       " 'result': ['你好。'],\n",
       " 'sn': '77906641641652880913'}"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# str 转换成 dict\n",
    "result_str = eval(result)\n",
    "result_str"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "c31030c7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'你好'"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 取出文本并将标点符号去掉\n",
    "txt = result_str[\"result\"][0][:-1]\n",
    "txt"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c03b7752",
   "metadata": {},
   "source": [
    "## 图灵机器人"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "5dad574b",
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests,json\n",
    "robot_key = \"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b83b10d8",
   "metadata": {},
   "outputs": [],
   "source": [
    "def robot(robot_key,text):\n",
    "    robot_url = \"http://openapi.turingapi.com/openapi/api/v2\"\n",
    "\n",
    "    payload = {\n",
    "        \"reqType\":0,\n",
    "        \"perception\": {\n",
    "            \"inputText\": {\n",
    "                \"text\": \n",
    "            },\n",
    "        },\n",
    "        \"userInfo\": {\n",
    "            \"apiKey\": robot_key,\n",
    "            \"userId\": \"001\"\n",
    "        }\n",
    "    }\n",
    "    res = requests.post(robot_url,data=json.dumps(payload))\n",
    "    return res.json()['results'][0]['values']['text']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "6dc7af27",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 青云客机器人\n",
    "def robot2(text):\n",
    "    url = \"http://api.qingyunke.com/api.php\"\n",
    "    payload = {\n",
    "        \"key\": \"free\",\n",
    "        \"appid\": 0,\n",
    "        \"msg\": text\n",
    "    }\n",
    "    r = requests.get(url, params=payload)\n",
    "    return r.json()['content']"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "62857dbc",
   "metadata": {},
   "source": [
    "## 用图灵接口的语音识别对话机器人\n",
    "1. 准备音频文件\n",
    "2. 调用百度语音识别-返回文本信息\n",
    "3. 调用图灵机器人-返回文本信息\n",
    "4. 调用百度语音合成"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "93325529",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "result saved as :result.wav\n"
     ]
    }
   ],
   "source": [
    "import TTS\n",
    "import speech_recognition\n",
    "from pydub import AudioSegment\n",
    "from pydub.playback import play\n",
    "\n",
    "# 准备音频文件\n",
    "r = speech_recognition.Recognizer()\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将数据保存到wav文件中\n",
    "with open(\"1.wav\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))\n",
    "\n",
    "# 调用百度语音识别\n",
    "token = ASR.fetch_token(API_KEY,SECRET_KEY)\n",
    "result = eval(ASR.asr(token))['result'][0]\n",
    "\n",
    "# 调用图灵机器人\n",
    "# robot(robot_key, result)\n",
    "\n",
    "# 调用青云客机器人\n",
    "robot2(result)\n",
    "\n",
    "# 语音合成\n",
    "# TTS.tts(token,robot(robot_key, result))\n",
    "TTS.tts(token, robot2(result))\n",
    "song = AudioSegment.from_wav('result.wav')\n",
    "play(song)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "16ed670b",
   "metadata": {},
   "source": [
    "## 语音合成"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "b464c910",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "result saved as :result.wav\n"
     ]
    }
   ],
   "source": [
    "import TTS\n",
    "TTS.tts(token,\"好困啊\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "07ce36fe",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Collecting pydub\n",
      "  Downloading pydub-0.25.1-py2.py3-none-any.whl (32 kB)\n",
      "Installing collected packages: pydub\n",
      "Successfully installed pydub-0.25.1\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "WARNING: You are using pip version 22.0.4; however, version 22.1 is available.\n",
      "You should consider upgrading via the 'd:\\anaconda3\\python.exe -m pip install --upgrade pip' command.\n"
     ]
    }
   ],
   "source": [
    "!pip install pydub"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "1228e92d",
   "metadata": {},
   "outputs": [],
   "source": [
    "from pydub import AudioSegment\n",
    "from pydub.playback import play\n",
    "\n",
    "song = AudioSegment.from_wav('1.wav')\n",
    "play(song)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0a7d0a5a",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
